package cn.xuanxuanyuhua.crm.shiro.realm;

import cn.xuanxuanyuhua.crm.domain.Employee;
import cn.xuanxuanyuhua.crm.service.IEmployeeService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component("crmRealm")
public class CRMRealm extends AuthorizingRealm{
    @Autowired
    public IEmployeeService service;

    @Autowired
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        super.setCredentialsMatcher(credentialsMatcher);
    }

    //做认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //类型转换,调用方法
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        //从数据库从查数据
        Employee employee = service.getInfoByUsername(upToken.getUsername());
        if (employee != null) {
            return new SimpleAuthenticationInfo(employee,employee.getPassword(),ByteSource.Util.bytes(employee.getName()),getName());
        }
        return null;
    }

    //做授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //创建要返回的授权信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //从身份集合中获取主身份信息
        Employee employee = (Employee) principalCollection.getPrimaryPrincipal();
        List<String> roles = new ArrayList<>();
        List<String> permissions = new ArrayList<>();
        //判断是否为超管
        if (employee.isAdmin()) {
            //增加角色
            roles.add("admin");
            //增加所有的权限
            permissions.add("*:*");
        } else{
            roles = service.getRolesByEmployeeId(employee.getId());
            permissions = service.getPermissionByEmployee(employee.getId());
        }
        //将角色和权限保存到授权信息中
        info.addRoles(roles);
        info.addStringPermissions(permissions);
        return info;
    }
}
